package com.ibeetl.cms.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.Enterprise;
import com.ibeetl.cms.entity.Excel;
import com.ibeetl.cms.service.BusinessProcessService;
import com.ibeetl.cms.service.EnterpriseService;
import com.ibeetl.cms.service.ExcelService;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.web.quer3.ExcelExamineQuery;
import com.ibeetl.cms.web.query.ExcelQuery;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * 报表导出接口
 */
@Controller
public class ExcelController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/excel";

    @Autowired
    FileService fileService;

    @Autowired
    CorePlatformService platformService;

    @Autowired
    EnterpriseService enterpriseService;

    @Autowired
    private BusinessProcessService businessProcessService;

    @Autowired
    ExcelService excelService;

    @GetMapping(MODEL + "/index.do")
    @Function("excel.enterprise")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/excel/index.html");
        view.addObject("search", ExcelQuery.class.getName());
        return view;
    }

    @PostMapping(MODEL + "/list.json")
    @Function("excel.check")
    @ResponseBody
    public JsonResult<PageQuery> list(ExcelQuery condtion) {
        try {
            PageQuery<Excel> page = condtion.getPageQuery();
            //业务事项
            if (condtion.getBusinessMatters() == null || condtion.getBusinessMatters() == "") {
                return JsonResult.failMessage("<font color=\"red\">业务事项</font>不能为空,请选择一个业务事项");
            } else if (condtion.getBusinessStateCode().equals(null) || condtion.getBusinessStateCode().equals("")) {
                return JsonResult.failMessage("<font color=\"red\">业务状态</font>不能为空,请选择一个业务状态");
            } else {
                common(condtion);
                excelService.queryByCondition(page);
                return JsonResult.success(page);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.failMessage("请求出现异常");
    }

    @PostMapping(MODEL + "/companyList.json")
    @Function("excel.enterprise")
    @ResponseBody
    public JsonResult<PageQuery> companyList(ExcelQuery condtion) {
        PageQuery<Excel> page = condtion.getPageQuery();
        //业务事项
        if (condtion.getBusinessMatters() == null || condtion.getBusinessMatters() == "") {
            return JsonResult.failMessage("<font color=\"red\">业务事项</font>不能为空,请选择一个业务事项");
        } else if (condtion.getBusinessStateCode().equals(null) || condtion.getBusinessStateCode().equals("")) {
            return JsonResult.failMessage("<font color=\"red\">业务状态</font>不能为空,请选择一个业务状态");
        } else {
            /**
             * 设置企业的oranezation
             */
            CoreUser user = platformService.getCurrentUser();
            Long userId = user.getId();
            Enterprise enterprise = enterpriseService.findenterprise(userId);
            String organizationCode = enterprise.getOrganizationCode();
            condtion.setOrganizationCode(organizationCode);
            common(condtion);
            excelService.queryByCondition(page);
            return JsonResult.success(page);
        }
    }

    //初审 ，复审报表导出

    @GetMapping(MODEL + "/check.do")
    @Function("excel.check")
    @ResponseBody
    public ModelAndView check() {
        ModelAndView view = new ModelAndView("/cms/excel/checkIndex.html");
        view.addObject("search", ExcelExamineQuery.class.getName());
        return view;
    }

    /**
     * 拨付明细导出
     *
     * @param response
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/excel/appropriationDetailsExport.json")
    @Function("excel.check")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response, ExcelQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此userService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate = "excelTemplates/admin/excel/detailsExcel.xls";
        PageQuery<Enterprise> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        if (condtion.getBusinessMatters() == null || condtion.getBusinessMatters() == "") {
            return JsonResult.failMessage("业务事项不能为空,请选择一个业务事项");
        } else if (condtion.getBusinessStateCode().equals(null) || condtion.getBusinessStateCode().equals("")) {
            return JsonResult.failMessage("业务状态不能为空,请选择一个业务状态");
        } else {
            common(condtion);
            List<Excel> list = excelService.queryByCondition(page).getList();
            if(null == list || list.size() == 0){
                return JsonResult.failMessage("可导出记录数为0");
            }
            try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
                if (is == null) {
                    throw new PlatformException("模板资源不存在：" + excelTemplate);
                }
                FileItem item = fileService.createFileTemp(condtion.getBusinessMatters() + "-拨付明细表.xls");
                OutputStream os = item.openOutpuStream();
                Context context = new Context();
                Map<String,String> getTailsMap = (Map) list.get(0).getTails();
                //20200401
                context.putVar("title", "金湾区"+getTailsMap.get("year")+"年度"+condtion.getBusinessMatters()+"拨付明细表");
               /* if ("4".equals(condtion.getBusinessStateCode())) {
                    context.putVar("title", "金湾区"+getTailsMap.get("year")+"年度"+condtion.getBusinessMatters()+"拨付明细表");
                }else{
                    context.putVar("title", "金湾区"+getTailsMap.get("year")+"年度"+condtion.getBusinessMatters()+"拨付明细表");
                }*/
                context.putVar("detailsExcel", list);
                JxlsHelper.getInstance().processTemplate(is, os, context);
                os.close();
                //下载参考FileSystemContorller
                return JsonResult.success(item.getPath());
            } catch (IOException e) {
                throw new PlatformException(e.getMessage());
            }
        }
    }


    /**
     * 业务报表导出
     *
     * @param response
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/excel/businessExport.json")
    //@Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult<String> businessExport(HttpServletResponse response, ExcelQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此userService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        PageQuery<Enterprise> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        if (condtion.getBusinessMatters() == null || condtion.getBusinessMatters() == "") {
            return JsonResult.failMessage("业务事项不能为空,请选择一个业务事项");
        } else if (condtion.getBusinessStateCode().equals(null) || condtion.getBusinessStateCode().equals("")) {
            return JsonResult.failMessage("业务状态不能为空,请选择一个业务状态");
        } else {
            common(condtion);
            List<Excel> list = excelService.queryByCondition(page).getList();
            if(null == list || list.size() == 0){
                return JsonResult.failMessage("可导出记录数为0");
            }
            try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(condtion.getExcelTemplate())) {
                if (is == null) {
                    throw new PlatformException("模板资源不存在：" + condtion.getExcelTemplate());
                }
                FileItem item = fileService.createFileTemp(condtion.getBusinessMatters() + "-申报信息导出.xls");
                OutputStream os = item.openOutpuStream();
                Context context = new Context();
                context.putVar("businessExport", list);
                Map<String,String> getTailsMap = (Map) list.get(0).getTails();
                context.putVar("title", "金湾区"+getTailsMap.get("year")+"年度"+condtion.getBusinessMatters()+"申报信息");
                JxlsHelper.getInstance().processTemplate(is, os, context);
                os.close();
                //下载参考FileSystemContorller
                return JsonResult.success(item.getPath());
            } catch (IOException e) {
                throw new PlatformException(e.getMessage());
            }
        }
    }

    /**
     * 企业业务报表导出
     *
     * @param response
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/excel/companyBusinessExport.json")
    //@Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult<String> companyBusinessExport(HttpServletResponse response, ExcelQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此userService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        PageQuery<Enterprise> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        if (condtion.getBusinessMatters() == null || condtion.getBusinessMatters() == "") {
            return JsonResult.failMessage("业务事项不能为空,请选择一个业务事项");
        } else if (condtion.getBusinessStateCode().equals(null) || condtion.getBusinessStateCode().equals("")) {
            return JsonResult.failMessage("业务状态不能为空,请选择一个业务状态");
        } else {
            CoreUser user = platformService.getCurrentUser();
            Long userId = user.getId();
            Enterprise enterprise = enterpriseService.findenterprise(userId);
            String organizationCode = enterprise.getOrganizationCode();
            condtion.setOrganizationCode(organizationCode);
            common(condtion);
            List<Excel> list = excelService.queryByCondition(page).getList();
            if(null == list || list.size() == 0){
                return JsonResult.failMessage("可导出记录数为0");
            }
            try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(condtion.getExcelTemplate())) {
                if (is == null) {
                    throw new PlatformException("模板资源不存在：" + condtion.getExcelTemplate());
                }
                FileItem item = fileService.createFileTemp(condtion.getBusinessMatters() + "-申报信息导出.xls");
                OutputStream os = item.openOutpuStream();
                Context context = new Context();
                context.putVar("businessExport", list);
                Map<String,String> getTailsMap = (Map) list.get(0).getTails();
                context.putVar("title", "金湾区"+getTailsMap.get("year")+"年度"+condtion.getBusinessMatters()+"申报信息");
                JxlsHelper.getInstance().processTemplate(is, os, context);
                os.close();
                //下载参考FileSystemContorller
                return JsonResult.success(item.getPath());
            } catch (IOException e) {
                throw new PlatformException(e.getMessage());
            }
        }
    }


    //获取业务事项和数据范围
    public void common(ExcelQuery condtion) {
        if (condtion.getBusinessMatters().equals("1")) {
            condtion.setClassname("industrial_talents");
            condtion.setExcelTemplate("excelTemplates/admin/excel/industrialTalentsExcel.xls");
            condtion.setBusinessMatters("产业人才补贴");
        } else if (condtion.getBusinessMatters().equals("2")) {
            condtion.setClassname("renting");
            condtion.setExcelTemplate("excelTemplates/admin/excel/rentingExcel.xls");
            condtion.setBusinessMatters("租房补贴");
        } else if (condtion.getBusinessMatters().equals("3")) {
            condtion.setClassname("doctoral_subsidy");
            condtion.setExcelTemplate("excelTemplates/admin/excel/doctoralSubsidyExcel.xls");
            condtion.setBusinessMatters("博士后在站补贴");
        } else if (condtion.getBusinessMatters().equals("4")) {
            condtion.setClassname("outbound_subsidy");
            condtion.setExcelTemplate("excelTemplates/admin/excel/outboundSubsidyExcel.xls");
            condtion.setBusinessMatters("博士后出站补贴");
        } else if (condtion.getBusinessMatters().equals("5")) {
            condtion.setClassname("highlevel_talents");
            condtion.setExcelTemplate("excelTemplates/admin/excel/highlevelTalentsExcel.xls");
            condtion.setBusinessMatters("高层次人才补贴");
        } else if (condtion.getBusinessMatters().equals("6")) {
            condtion.setClassname("skill");
            condtion.setExcelTemplate("excelTemplates/admin/excel/skillExcel.xls");
            condtion.setBusinessMatters("技能提升奖励");
        } else if (condtion.getBusinessMatters().equals("7")) {
            condtion.setClassname("professional_technology");
            condtion.setExcelTemplate("excelTemplates/admin/excel/professionalTechnologyExcel.xls");
            condtion.setBusinessMatters("专业技术提升奖励");
        } else if (condtion.getBusinessMatters().equals("8")) {
            condtion.setClassname("buy_house_subsidies");
            condtion.setExcelTemplate("excelTemplates/admin/excel/buyHouseSubsidiesExcel.xls");
            condtion.setBusinessMatters("购房补贴");
        } else if (condtion.getBusinessMatters().equals("14")) {
            condtion.setClassname("medical_care");
            condtion.setExcelTemplate("excelTemplates/admin/excel/buyHouseSubsidiesExcel.xls");
            condtion.setBusinessMatters("健康体检");
        } else if (condtion.getBusinessMatters().equals("15")) {
            condtion.setClassname("insurance");
            condtion.setExcelTemplate("excelTemplates/admin/excel/buyHouseSubsidiesExcel.xls");
            condtion.setBusinessMatters("健康保险");
        }
//        else if(condtion.getBusinessMatters().equals("9")){
//            condtion.setClassname("medical_care");
//            condtion.setExcelTemplate("excelTemplates/admin/excel/medicalCareExce.xls");
//            condtion.setBusinessMatters("医疗管理");
//        }
        //业务状态
        if (condtion.getBusinessStateCode().equals("1")) {
            condtion.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        } else if (condtion.getBusinessStateCode().equals("2")) {
            condtion.setBusinessStateCode(ProcessConstant.TO_FINALCHECK);
        } else if (condtion.getBusinessStateCode().equals("3")) {
            condtion.setBusinessStateCode(ProcessConstant.DONE);
        }
    }
}


